package com.foodlocker.http;


import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import com.foodlocker.bean.Machine;
import com.foodlocker.bean.Order;
import com.foodlocker.common.CommonFunction;
import com.foodlocker.common.Constant;
import com.foodlocker.common.UniversalHttpPost;

import com.foodlocker.machine.MachineLoginAct;
import com.foodlocker.sqlite.OrderDao;


import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.JsonReader;
public class PollingService extends Service{
//	 private Notification mNotification;
//	  private NotificationManager mManager;
	OrderDao orderDao;
	  public static final String ACTION = "com.example.http.PollingService";
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		// initNotifiManager();
		 orderDao= new OrderDao(PollingService.this);
		  MyReceiver myReceiver = new MyReceiver();  
          IntentFilter filter = new IntentFilter();  
          filter.addAction(Constant.ACTION_PALY);  
          filter.addAction(Constant.ACTION_PAUSE);  
          registerReceiver(myReceiver, filter);  
	}

	@Override
	@Deprecated
	public void onStart(Intent intent, int startId) {
		
		new PollingStepByStep().start();
	//   System.out.println(" all data in sqlite"  +orderDao.queryAll());
	}
	 @Override
	    public void onDestroy() {
	        super.onDestroy();
	        System.out.println("Service:onDestroy");
	    }

      class PollingStepByStep extends Thread{

			@Override
			public void run() { 
				//这里有两个任务， 1是拉取卖家已确认的订单，		      
				dealTobeConfirmdedOrder();	
			 // 任务2是拉取收货前同意退款的订单。			
				
			 // 任务3提交已取走但未及时更新的订单
				updateTakedOrder();
			}
        }  //end of Thread 
      
      private void dealTobeConfirmdedOrder(){
    	  // 任务1分，散步 1是拉取订单，存（replace）本地数据。2,告知服务器已成功接收。3，修改本地订单状态。				
    	    String[] params= new String[3];
            params[0]=Constant.BaseUrl+Constant.MachineUrl;
            params[1]="frequentlyPull"; //PostCod
            JSONObject jsonData=new JSONObject();	
            JSONObject simpleMachineJO= new JSONObject();
             simpleMachineJO.put(Machine.ID, Constant.machineJO.getInt(Machine.ID));
             simpleMachineJO.put(Machine.SECRET, Constant.machineJO.getString(Machine.SECRET));
            jsonData.put("machine", simpleMachineJO);
        	params[2]=jsonData.toString();
        	 Map<String,Object> map=  UniversalHttpPost.doPost(params);	        	 
        	 String PostResult=(String) map.get("PostResult");		 
			 boolean networkstate=(Boolean) map.get("PostState");
			 if(!networkstate){ System.out.println("frequentlyPull   no network "); return; }
	
			 JSONObject json = null;
			    int resultCode=-1;
				String resultInfo="";
				String affair="";				
				JSONObject jo;
				try{
			     json= JSONObject.fromObject(PostResult);
			     resultCode=json.getInt("resultCode");
			     resultInfo=json.getString("resultInfo");	
			     affair =json.getString("affair");	
			     jo= json.getJSONObject("jo");
				}catch(JSONException e){
					// CommonFunction.alert(PollingService.this, "失败", "数据解析错误");
					System.out.println("frequentlyPull failed 回传数据解析异常");
					 return;
				}			
				if(resultCode==1){ 
				// 	CommonFunction.alert(PollingService.this, "失败", resultInfo);
					System.out.println("frequentlyPull failed "+ resultInfo);
					return; }
				if(resultCode==2){
					JSONArray orderJA= jo.getJSONArray("orders");
					if(orderJA.size()<=0){return;}
			 	JSONArray insertedOrderJA=new OrderDao(PollingService.this).insert(orderJA);
			 	if(insertedOrderJA.size()<=0){return;}
			 	  params[0]=Constant.BaseUrl+Constant.MachineUrl;
		            params[1]="changeOrderState"; //PostCod
		            jsonData.put("machine", Constant.machineJO.toString());
		            jsonData.put("orders", insertedOrderJA);
		            jsonData.put("oldState", 11);
		            jsonData.put("newState", 12);
		        	params[2]=jsonData.toString();
		             map=  UniversalHttpPost.doPost(params);	        	 
		               PostResult=(String) map.get("PostResult");		 
				      networkstate=(Boolean) map.get("PostState");
				      if(!networkstate){ System.out.println(" confirmOrder  no network "); return; }
						
							try{
						     json= JSONObject.fromObject(PostResult);
						     resultCode=json.getInt("resultCode");
						     resultInfo=json.getString("resultInfo");	
						     affair =json.getString("affair");	
						     jo= json.getJSONObject("jo");
							}catch(JSONException e){
								// CommonFunction.alert(PollingService.this, "失败", "数据解析错误");
								System.out.println(" confirmOrder  failed 回传数据解析异常");
								 return;
							}			
							if(resultCode==1){ 
							// 	CommonFunction.alert(PollingService.this, "失败", resultInfo);
								System.out.println(" confirmOrder failed "+ resultInfo);
								return; }
							if(resultCode==2){
								orderJA=jo.getJSONArray("orders");
								OrderDao orderDao= new OrderDao(PollingService.this);
								for(int i=0;i<orderJA.size();i++){
									orderDao.updateOrderState(orderJA.getJSONObject(i).getLong(Order.ID), 12);
								}
								
							}
				}
      }
      
      private void updateTakedOrder(){
    	  // 任务1分，散步 1是拉取订单，存（replace）本地数据。2,告知服务器已成功接收。3，修改本地订单状态。				
    	    String[] params= new String[3];
            params[0]=Constant.BaseUrl+Constant.MachineUrl;
            params[1]="orderTaked"; //PostCod
            JSONObject jsonData=new JSONObject();	
            JSONObject simpleMachineJO= new JSONObject();
             simpleMachineJO.put(Machine.ID, Constant.machineJO.getInt(Machine.ID));
             simpleMachineJO.put(Machine.SECRET, Constant.machineJO.getString(Machine.SECRET));
            jsonData.put("machine", simpleMachineJO);  
	         JSONArray orders= new OrderDao(getApplicationContext()).queryTakedOrder();
	         if(orders.size()==0) return;
	         jsonData.put("orders",orders);      
        	params[2]=jsonData.toString();
        	 Map<String,Object> map=  UniversalHttpPost.doPost(params);	        	 
        	 String PostResult=(String) map.get("PostResult");		 
			 boolean networkstate=(Boolean) map.get("PostState");
			 if(!networkstate){ System.out.println("frequentlyPull   no network "); return; }
	
			 JSONObject json = null;
			    int resultCode=-1;
				String resultInfo="";
				String affair="";				
				JSONObject jo;
				try{
			     json= JSONObject.fromObject(PostResult);
			     resultCode=json.getInt("resultCode");
			     resultInfo=json.getString("resultInfo");	
			     affair =json.getString("affair");	
			     jo= json.getJSONObject("jo");
				}catch(JSONException e){
					// CommonFunction.alert(PollingService.this, "失败", "数据解析错误");
					System.out.println("updateOrderTaked Duty failed 回传数据解析异常");
					 return;
				}			
				if(resultCode==1){ 
					System.out.println("updateOrderTaked Duty  failed "+ resultInfo);
					return; }
				if(resultCode==2){
					JSONArray orderJA= jo.getJSONArray("orders");
					new OrderDao(PollingService.this).updateOrdersState(orderJA, 22);	 	 
				}
      }
      
   private void  dealMachineMessage(){
	   
	   //通过消息，来确定自提柜要完成哪些更新。
	   String[] params= new String[3];
       params[0]=Constant.BaseUrl+Constant.MachineUrl;
       params[1]="frequentlyPull"; //PostCod
       JSONObject jsonData=new JSONObject();	
       jsonData.put("machine", Constant.machineJO.toString());
   	params[2]=jsonData.toString();
   	 Map<String,Object> map=  UniversalHttpPost.doPost(params);	        	 
   	 String PostResult=(String) map.get("PostResult");		 
		 boolean networkstate=(Boolean) map.get("PostState");
		 if(!networkstate){ System.out.println("frequentlyPull   no network "); return; }

		 JSONObject json = null;
		    int resultCode=-1;
			String resultInfo="";
			String affair="";				
			JSONObject jo;
			try{
		     json= JSONObject.fromObject(PostResult);
		     resultCode=json.getInt("resultCode");
		     resultInfo=json.getString("resultInfo");	
		     affair =json.getString("affair");	
		     jo= json.getJSONObject("jo");
			}catch(JSONException e){
				// CommonFunction.alert(PollingService.this, "失败", "数据解析错误");
				System.out.println("frequentlyPull failed 回传数据解析异常");
				 return;
			}			
			if(resultCode==1){ 
			// 	CommonFunction.alert(PollingService.this, "失败", resultInfo);
				System.out.println("frequentlyPull failed "+ resultInfo);
				return; }
			if(resultCode==2){
				JSONArray orderJA= jo.getJSONArray("orders");
				if(orderJA.size()<=0){return;}
		 	JSONArray insertedOrderJA=new OrderDao(PollingService.this).insert(orderJA);
			}
   }
        
        class TakeUpdateToServerThread extends Thread{

   			@Override
   			public void run() {
   				// TODO Auto-generated method stub
   			
   			}  //end of run()
           	
           }  //end of Thread 
        
	    private class MyReceiver extends BroadcastReceiver {  
	        @Override  
	        public void onReceive(Context context, Intent intent) {  
	         //   Log.i(tag, intent.getAction());  
	            try {  
	                if (Constant.ACTION_PALY.equals(intent.getAction())) {  
	                    PollingService.this.play();  
	                } else if (Constant.ACTION_PAUSE.equals(intent.getAction())) {  
	                	PollingService.this.pause();  
	                }  
	            } catch (Exception e) {  
	                e.printStackTrace();  
	            }  
	        }  
	    }  
	    
	    public void play() {  
	    	System.out.println( "my function Paly()....");  
	    }  
	  
	    public void pause() {  
	    	System.out.println( "my function Pause()....");  
	    }  
	 //初始化通知栏配置
  /*  private void initNotifiManager() {
        mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        int icon = R.drawable.ic_launcher;
        mNotification = new Notification();
        mNotification.icon = icon;
        mNotification.tickerText = "New Message";
        mNotification.defaults |= Notification.DEFAULT_SOUND;
        mNotification.flags = Notification.FLAG_AUTO_CANCEL;
    }
    //弹出Notification
    private void showNotification() {
        mNotification.when = System.currentTimeMillis();
        //Navigator to the new activity when click the notification title
        Intent i = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i,
                Intent.FLAG_ACTIVITY_NEW_TASK);
        mNotification.setLatestEventInfo(this,
                getResources().getString(R.string.app_name), "You have new message!", pendingIntent);
        mManager.notify(0, mNotification);
    }*/
	
	 

     
     
}
